package com.project.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.Power;
import com.project.bean.User;
import com.project.service.IPowerService;
import com.project.service.IUserService;
import com.project.util.StringUtil;
import com.project.util.SysToken;
import com.project.vo.PowerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lovo
 * @since 2022-08-18
 */
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
IUserService userService;
@Autowired
IPowerService powerService;
    @GetMapping("login/{userName}/{password}")
    public String login(@PathVariable("userName")String userName,
                        @PathVariable("password")String password){
        QueryWrapper qw=new QueryWrapper();
        qw.eq("userName",userName);
        qw.eq("pwd",password);

        User user=  userService.getOne(qw);
        if(null==user){
            return StringUtil.RESULT_ERROR;
        }else {
            //验证通过
            QueryWrapper query=new QueryWrapper();
            query.eq("fk_userId",user.getId());
            List<Power> powerList= powerService.list(query);
            PowerVo powerVo=new PowerVo();
            powerVo.setUser(user);
            powerVo.setPowerList(powerList);
            String powerStr=  JSON.toJSONString(powerVo);
            return     SysToken.createToken(powerStr);
        }
    }
    @RequestMapping("logins")
    public String logins(String userName, String pwd, HttpServletRequest req){
        QueryWrapper qw=new QueryWrapper();
        qw.eq("userName",userName);
        qw.eq("pwd",pwd);

        User user=  userService.getOne(qw);
        if (user!=null){
            req.getSession().setAttribute("loginUser",user);
            return "ok";
        }
        return "no";
    }

    @RequestMapping("getLoginUser")
    public User getLoginUser(HttpServletRequest req){
        return (User) req.getSession().getAttribute("loginUser");
    }
}
